package com.eptok.gw.szcups.web.listener;

import java.io.File;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import ys8583.parse.ConfigParser;

import com.eptok.gw.szcups.common.KeyContainer;
import com.eptok.gw.szcups.common.PropertyLoader;
import com.eptok.gw.szcups.cups.CupsMessageControl;
import com.eptok.gw.szcups.monitor.Monitor;
import com.eptok.gw.szcups.thread.ReveralThread;

/**
 *@author:heqishan, Email:heqishan@gmail.com
 *2013-3-1 下午03:23:07
 */
public class SystemListener implements ServletContextListener {

	private ReveralThread reveralThread;
	
	public void contextInitialized(ServletContextEvent event) {
		try{
			
			//web路径
			String webContent = event.getServletContext().getRealPath("/");
			
			//加载配置文件
			PropertyLoader.getInstance().loadProperties(webContent);
			
			//判断商户连接是否已经有key
			if(KeyContainer.getInstance().getMerZAK() == null || "".equals(KeyContainer.getInstance().getMerZAK())){
				Monitor.getInstance().setMerchantHasKey(false);
			}else{
				Monitor.getInstance().setMerchantHasKey(true);
			}
			
			//初始化8583包
			ConfigParser configParser = new ConfigParser();
			configParser.parse(new File(webContent + File.separator + "conf" + 
					File.separator + "sz_cups_template.xml"));
			
			//初始化与银联通讯的client与server
			CupsMessageControl.getInstance().initialized();
			
			reveralThread = new ReveralThread();
			reveralThread.start();
			
		}catch(Exception e){
			e.printStackTrace();
			
		}
		
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		try{
			//关闭交易开关
			Monitor.getInstance().setMasterSwitch(false);
			//将可变参数保存到文件
			PropertyLoader.getInstance().storeConfig();
			CupsMessageControl.getInstance().destroyed();
			reveralThread.setIsrun(false);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
}
